#-*- coding: utf-8 -*-
from django.db import models
import exceptions
import datetime
import urllib2
import xml.etree.ElementTree as ET

import assetParser as aparser

class AssetManager(models.Manager):
    def create_asset(self, assetID, assetParentID, assetLocationID, assetTypeID, assetQuantity, assetFlag, assetSingleton, assetRawQuantity):
        asset = self.create(assetID = assetID, assetParentID = assetParentID, assetLocationID = assetLocationID, assetTypeID = assetTypeID, assetQuantity = assetQuantity, assetFlag = assetFlag, assetSingleton = assetSingleton, assetRawQuantity = assetRawQuantity)
        #do something with asset
        return asset
    

class Asset(models.Model):
    #itemID
    assetID = models.IntegerField.primary_key
    #parent itemID
    assetParentID = models.IntegerField
    #typeID
    #assetName = models.CharField
    #locationID
    assetLocationID = models.IntegerField
    #typeID
    assetTypeID = models.IntegerField
    #quantity
    assetQuantity = models.IntegerField
    #flag
    assetFlag = models.IntegerField
    #singleton
    assetSingleton = models.IntegerField
    #rawQuantity
    assetRawQuantity = models.IntegerField
    
    objects = AssetManager()
    
# asset = Asset.objects.create_asset(assetID, assetParentID, assetLocationID, assetTypeID, assetQuantity, assetFlag, assetSingleton, assetRawQuantity) 
  
    
    #check tastypie for django !!!! 
    def catchAssetsApi(self, url):
    #récupère le xml et crée un objet ElementTree xml
        try:
            xml = urllib2.urlopen(url)
            tree = ET.parse(xml)
            root = tree.getroot()
            return root
        except Exception, e:
            print(e)

    def catchAssetsApiFile(self, xmlfile):
    #récupère le xml et crée un objet ElementTree xml
        try:
            tree = ET.parse(xmlfile)
            root = tree.getroot()
            return root
        except Exception, e:
            print(e)


        #retourne les top elements (current time, cachedUntil root len)
        def printApiMetadata(root):
            print "nb in root: ", len(root)
            print "Current time: ", root[0].text
            print "CachedUntil: ", root[2].text
    #renvoyer une liste avec ces valeurs
    
    def parse_subrow(self, node, attribute, attributeValue, subtag):
        y = 0
        control = True
        subrow = node.iterfind(".//*[@{0}='{1}']/{2}".format(attribute, attributeValue, subtag))
        while control:
            try:
                if subrow is not None:   
                    subElement = subrow.next()
                    if subElement is not None:
                        y+=1
                        subAsset = Asset.objects.create_asset(subElement.get('itemID'), node.get('itemID'), subElement.get('locationID'), subElement.get('typeID'), subElement.get('quantity'), subElement.get('flag'), subElement.get('singleton'), subElement.get('rawQuantity'))
                        #sais pas si nécessaire ?
                        subAsset.save() 
                        print subAsset.assetID  
#                         subElement.set ('Lv', y)
#                         print "Sub-Element : {0} - {1} : {2} | __parent ID {3}".format( node.get('Lv'), subElement.get('Lv'), subElement.get('itemID'), node.get('itemID'))
#                         self.assetID = subElement.get('itemID')
#                         self.assetParentID = node.get('itemID')
#                         self.assetLocationID = subElement.get('locationID')
#                         self.assetTypeID = subElement.get('typeID')
#                         self.assetQuantity = subElement.get('quantity')
#                         self.assetFlag = subElement.get('flag')
#                         self.assetSingleton = subElement.get('singleton')
#                         self.assetRawQuantity = subElement.get('rawQuantity')
#                         print "Parent ID/{0} - ID: {1}/Type: {2}/Loc: {3}/Q: {4}/F: {5}/S: {6}/RWQ: {7}".format(self.assetParentID, self.assetID, self.assetTypeID, self.assetLocationID, self.assetQuantity, self.assetFlag, self.assetSingleton, self.assetRawQuantity)
                        #print_row(subElement, node)
                        #parse_subrow(subElement, "name", "contents", "row")
            except StopIteration:
                control = False

    # fonction qui parcourt tous les noeuds avec comme tag "sutbag" contenus dans "node" dont les parents sont des noeuds qui ont un attribut "attribute" qui vaut "attributeValue"
    def parse_row(self, node, attribute, attributeValue, subtag):
        y=0
        control= True
        row = node.iterfind(".//*[@{0}='{1}']/{2}".format(attribute, attributeValue, subtag))
        while control:
            try:
                if row is not None:
                    y+=1
                    element = row.next()
                    asset = Asset.objects.create_asset(element.get('itemID'), node.get('itemID'), element.get('locationID'), element.get('typeID'), element.get('quantity'), element.get('flag'), element.get('singleton'), element.get('rawQuantity'))
                    #sais pas si nécessaire ?
                    asset.save()
                    print asset.assetID
#                     element.set('Lv', y)
                    #print element.get('Lv'), " - ", element.get('itemID') 
                    #print_row(element, node)
                    self.parse_subrow(element, "name", "contents", "row")
                    #ARRETE ICI CONTINUER MODEL PLUS VIEW AVEC BUTTON( INDEX) 2 EME VUE RESULTATS 
                    
                    #parse_subrow(element, "name", "contents", "row")
            except StopIteration:
                control = False
    
        def api_refresh(self):
            xmlFile = 'c:/wamp/www/eve_api_test/AssetList.xml'
            root = self.catchAssetsApiFile(xmlFile)
            #api metadata ??? 
            aparser.printApiMetadata(root)
            aparser.parse_row(root, "name", "assets", "row")
            #fill the api info in the model variables => here or in parser ?....
    
        

